﻿using InCom.API.Protocols;
using InCom.API.Protocols.Entitys;
using InCom.SyncStatus;
using InCom.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace inCom补发请求端
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
            long curCount = 0;
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                while (true)
                {

                    //结果条数
                    long result = SyncPointManager.Instance.ReceiveRealTimeDataCount - curCount;

                    //当前条数
                    curCount = SyncPointManager.Instance.ReceiveRealTimeDataCount;



                    TerminaRegist(System.Linq.Enumerable.Range(1, 255).Select(p => (uint)p).ToList());
                    Console.WriteLine("注册终端集合,接收数据条数{0:F2}", result / 20.00);
                    System.Threading.Thread.Sleep(1000 * 200);

                    foreach (var item in InCom.Utilities.ThreadManager.Instance.RuningTasks.ToArray())
                    {
                        Console.WriteLine("taskid:{0},Threadid:{1}", item.Id, item.TaskThread == null ? "末知" : "" + item.TaskThread.ManagedThreadId);
                    }
                    Console.WriteLine("");
                    Console.WriteLine("");
                    Console.WriteLine("");
                    Console.WriteLine("");
                }
            });
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            InCom.OTM.Adapters.SyncStatusAdapter.Instance.StartSyncStatus();

            System.Threading.Thread thr = null;


            Task task = new Task(() =>
            {
                thr = System.Threading.Thread.CurrentThread;
                while (true)
                {
                    System.Threading.Thread.Sleep(1000 * 5);
                }
            });
            task.Start();



            Task.Factory.StartNew(() =>
            {


                string readline = Console.ReadLine();
                if (readline == "st")
                {
                    Console.WriteLine("10秒强制关闭");
                    //结束数据
                    thr.Abort();
                    System.Threading.Thread.Sleep(1000 * 10);
                    task.Dispose();
                    Console.WriteLine("强制停止Task");
                }

                while (true)
                {
                    readline = Console.ReadLine();

                    try
                    {
                        int taskid = int.Parse(readline.ToLower().Replace("k", ""));
                        int thrid = ThreadManager.Find(taskid).TaskThread.ManagedThreadId;
                        var thrx = ThreadManager.Find(taskid).TaskThread;
                        thrx.Abort();
                        Console.WriteLine("强制停止Task{0},ThreadID:{1}", taskid, thrid);

                    }
                    catch
                    {
                        Console.WriteLine("请输入 要关闭的线程ID,如: k123,表示关闭TASKid为123的Thread");
                        foreach (var item in InCom.Utilities.ThreadManager.Instance.RuningTasks)
                        {
                            Console.WriteLine("taskid:{0},Threadid:{1},sta:{2},IsFaulted:{3},{4}", item.Id, item.TaskThread == null ? "末知" : "" + item.TaskThread.ManagedThreadId, item.Status, item.IsFaulted,item.LastActiveTime.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        }

                    }


                }

            });

        }


        #region 向终端进行反注册指令

        /// <summary>
        /// 需要向incom进行注册的终端号集合
        /// 向incom注册终端,获取实时数据
        /// </summary>
        /// <param name="terminalCodes">需要注册的终端编号</param>
        public void TerminaRegist(List<uint> terminalCodes)
        {
            if (terminalCodes == null)
            {
                return;
            }

            InCom.API.Protocols.Entitys.TerminalRegistrationEntity ent = new TerminalRegistrationEntity();
            ent.Terminal = terminalCodes;
            //注册终端协议解析器
            var regParse = PluginModulesManager.Instance.GetTcpParse(ent.MSGSEQ);
            if (regParse != null)
            {
                //向incom广播需要终端数据
                SyncPointManager.Instance.Broadcast(regParse.Create(ent), SyncPointType.InCom);
            }

        }

        #endregion
        /// <summary>
        /// 注册指定终端获取实时数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Click(object sender, RoutedEventArgs e)
        {
            uint ter;
            uint.TryParse(textBox.Text, out ter);

            TerminaRegist(new List<uint> { ter });
        }


        System.Collections.Concurrent.ConcurrentDictionary<int, System.Threading.Tasks.Task> TaskDic = new System.Collections.Concurrent.ConcurrentDictionary<int, Task>();

        System.Collections.Concurrent.ConcurrentDictionary<int, System.Threading.Thread> thrdic = new System.Collections.Concurrent.ConcurrentDictionary<int, System.Threading.Thread>();



        /// <summary>
        /// task线程外部关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            #region TASK线程管理
            int num = 30;
            for (int i = 0; i < num; i++)
            {
                Task task = new Task(() =>
                {
                    var thr = System.Threading.Thread.CurrentThread;

                    if (!thrdic.TryAdd(thr.ManagedThreadId, thr))
                    {
                        Console.WriteLine("Thread运行中..id" + thr.ManagedThreadId);
                    }

                    while (true)
                    {
                        System.Threading.Thread.Sleep(1000 * 5);
                    }
                });
                task.Start();
                if (!TaskDic.TryAdd(task.Id, task))
                {
                    Console.WriteLine("TASK运行中..id" + task.Id);
                }

            }

            Task.WaitAll(TaskDic.Values.ToArray(), 2000);
            Console.WriteLine(num + "个TASK任务创建,在命令行中使用st进行关闭");

            #endregion
            button1.IsEnabled = false;
            guanbi.IsEnabled = !button1.IsEnabled;

        }

        /// <summary>
        /// 关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void guanbi_Click(object sender, RoutedEventArgs e)
        {



            var c = thrdic.Count;
            Console.WriteLine("10秒强制关闭共:{0}个线程", c);
            foreach (var item in thrdic)
            {
                item.Value.Abort();
            }
            //task状态切换时间
            System.Threading.Thread.Sleep(1000 * 1);
            foreach (var item in TaskDic)
            {
                item.Value.Dispose();
            }

            TaskDic.Clear();
            thrdic.Clear();
            Console.WriteLine("强制停止Task");

            button1.IsEnabled = true;
            guanbi.IsEnabled = false;

        }
        Random dom = new Random();
        /// <summary>
        /// 线程按钮事件.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btntaskThread_Click(object sender, RoutedEventArgs e)
        {



            var sss = System.Threading.Thread.CurrentContext;

            TaskEx task = new TaskEx(() =>
            {
                //填充当前Task的线程属性
                ThreadManager.FillTaskExThread();
                int s = dom.Next(1, 50);
                while (true)
                {
                    s++;
                    System.Threading.Thread.Sleep(1000);
                    //更新当前Task最后状态时间
                    ThreadManager.UpdateTaskLastActiveTime();
                    Console.WriteLine("taskid:{0},Threadid:{1}",Task.CurrentId,System.Threading.Thread.CurrentThread.ManagedThreadId);
                    continue;

                    if (s > 50)
                    {
                        bool vde = false;
                        #region 关闭线程代码
                        //关闭线程
                        var tas = ThreadManager.Find(Task.CurrentId == null ? 0 : Task.CurrentId.Value); ;
                        //指定当前TASK所使用的当前线程
                        if (tas != null)
                        {
                            Console.WriteLine("taskid:{0},Threadid:{1},CurThreadid:{2},ThreadName:{3} 结束", tas.Id, tas.TaskThread.ManagedThreadId, System.Threading.Thread.CurrentThread.ManagedThreadId, tas.ThreadName);
                            tas.TaskThread.Abort();
                        }
                        #endregion

                    }


                }
            })
            { ThreadName = "TaskName ", AutoReRun = true };



            InCom.Utilities.ThreadManager.Instance.Add(task);
            task.Start();
            task.ThreadName += task.Id;


        }

        /// <summary>
        /// 向节点发送查询指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void button2_Click(object sender, RoutedEventArgs e)
        {

            InCom.API.Protocols.Entitys.TerminalOnLineStatus ent = new TerminalOnLineStatus() {  TerminalCodes =new List<uint>() { 222} };
 
            //注册终端协议解析器
            var regParse = PluginModulesManager.Instance.GetTcpParse(ent.MSGSEQ);
            if (regParse != null)
            {
                //向incom广播需要终端数据
                SyncPointManager.Instance.Broadcast(regParse.Create(ent), SyncPointType.InCom);
            }

        }
    }
}
